import path from 'path';
const { flipHorizontal, flipVertical, create3DRotationGIF,imgresize } = await import('./image/imageflip.js');
import App from '../App.js';
import { downloadImage } from './image/image-url.js';
import{MurasamePath}from'../path.js';
var imgpath = path.join(MurasamePath,'apps','local_apps','image','data');
export * from 'oicq';

let app = App.init({
    id: 'image',
    name: '图形对称'
})

app.reg({
    Horizontal_a: {
        rule: /^(#)?(左)?对称.*$/,
        fn: h_a,
        name: "左对称"
    },
    Horizontal_b: {
        rule: /^(#)?右对称.*$/,
        fn: h_b,
        name: "右对称"
    },
    Vertical_a: {
        rule: /^(#)?上对称.*$/,
        fn: v_a,
        name: "上对称"
    },
    Vertical_b: {
        rule: /^(#)?下对称.*$/,
        fn: v_b,
        name: "下对称"
    },
    Rotation3d: {
        rule: /^(#)?3d转.*$/,
        fn: r_3d,
        name: "3d转"
    },
    Imgresize: {
         rule: /^(#)?缩放.*$/,
        fn: img_resize,
        name: "尺寸缩放"
    }
})
async function img_resize(e) {
    const reply = await getReplyMessage.call(this, e);
    if (!reply?.message?.[0]?.type == "image") {
        return e.reply("请at要处理的图片");
    }

    console.log("----------------下载待处理图片--------------------");
    console.log(reply.message[0].url);
    console.log("---------------------url-------------------------");

    const k = await getParameterK(e);
    console.log("参数值：", k);
    await processImage(e, reply.message[0].url, imgresize, k);
}

async function getReplyMessage(e) {
    if (this.e.getReply) {
        return await this.e.getReply();
    } else if (this.e.source) {
        if (this.e.group?.getChatHistory) {
            return (await this.e.group.getChatHistory(this.e.source.seq, 1)).pop();
        } else if (this.e.friend?.getChatHistory) {
            return (await this.e.friend.getChatHistory(this.e.source.time, 1)).pop();
        }
    }
    return null;
}

async function getParameterK(e) {
    let text;
    for (const i of e.message) {
        if (i.type == 'text') {
            text = i.text.match(/\d+(?:\.\d+)?/)?.[0];
            break;
        }
    }
    return Number(text) || 0.5;
}

async function processImage(e, url, processor, k = 1) {
    try {
        const houzhui = await getImageExtension(url);
        if (!['.jpg', '.png', '.gif'].includes(houzhui)) {
            return e.reply(`不支持的图片类型：${houzhui}`);
        }

        e.reply("图片正在处理中...请稍后", false, { recallMsg: 5 });
        const inputFile = `start${houzhui}`;
        const outputFile = `result${houzhui}`;

        await downloadImage(url, imgpath, inputFile);
        await processor(
            path.join(imgpath, inputFile),
            path.join(imgpath, outputFile),
            k,
            houzhui
        );

        const message = [
            "处理成功：",
            segment.image(path.join(imgpath, outputFile)),
        ];
        e.reply(message, false, { recallMsg: 0 }, true);
    } catch (err) {
        console.error('处理失败:', err.message);
        e.reply("处理失败");
    }
}

async function r_3d(e) {
    const reply = await getReplyMessage.call(this, e);
    if (!reply?.message?.[0]?.type == "image") {
        return e.reply("请at要处理的图片");
    }

    console.log("----------------下载待处理图片--------------------");
    console.log(reply.message[0].url);
    console.log("---------------------url-------------------------");

    try {
        const houzhui = await getImageExtension(reply.message[0].url);
        if (!['.jpg', '.png', '.gif'].includes(houzhui)) {
            return e.reply(`不支持的图片类型：${houzhui}`);
        }

        e.reply("图片正在处理中...请稍后", false, { recallMsg: 5 });
        const inputFile = `start${houzhui}`;


        await downloadImage(reply.message[0].url, imgpath, inputFile);
        await create3DRotationGIF(
            path.join(imgpath, inputFile),
            path.join(imgpath, 'result.gif'),
            houzhui
        );

        const message = [
            "处理成功：",
            segment.image(path.join(imgpath, 'result.gif')),
        ];
        e.reply(message);
    } catch (err) {
        console.error('处理失败:', err.message);
        e.reply("处理失败");
    }
}

async function h_a(e) {
    const reply = await getReplyMessage.call(this, e);
    if (!reply?.message?.[0]?.type == "image") {
        return e.reply("请at要处理的图片");
    }

    console.log("----------------下载待处理图片--------------------");
    console.log(reply.message[0].url);
    console.log("---------------------url-------------------------");

    const k = await getParameterK(e);
    console.log("参数值：", k);
    await h(e, k, reply.message[0].url);
}

async function h_b(e) {
    const reply = await getReplyMessage.call(this, e);
    if (!reply?.message?.[0]?.type == "image") {
        return e.reply("请at要处理的图片");
    }

    console.log("----------------下载待处理图片--------------------");
    console.log(reply.message[0].url);
    console.log("---------------------url-------------------------");

    const k = await getParameterK(e);
    console.log("参数值：", k);
    await h(e, k * -1, reply.message[0].url);
}

async function v_a(e) {
    const reply = await getReplyMessage.call(this, e);
    if (!reply?.message?.[0]?.type == "image") {
        return e.reply("请at要处理的图片");
    }

    console.log("----------------下载待处理图片--------------------");
    console.log(reply.message[0].url);
    console.log("---------------------url-------------------------");

    const k = await getParameterK(e);
    console.log("参数值：", k);
    await v(e, k, reply.message[0].url);
}

async function v_b(e) {
    const reply = await getReplyMessage.call(this, e);
    if (!reply?.message?.[0]?.type == "image") {
        return e.reply("请at要处理的图片");
    }

    console.log("----------------下载待处理图片--------------------");
    console.log(reply.message[0].url);
    console.log("---------------------url-------------------------");

    const k = await getParameterK(e);
    console.log("参数值：", k);
    await v(e, k * -1, reply.message[0].url);
}

async function h(e, k, img1) {
    await processImage(e, img1, flipHorizontal, k);
}

async function v(e, k, img1) {
    await processImage(e, img1, flipVertical, k);
}

async function getImageExtension(url) {
    try {
        const headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Sec-Fetch-Site': 'none',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-User': '?1',
            'Sec-Fetch-Dest': 'document',
        };

        const response = await fetch(url, {
            method: 'GET',
            headers: headers,
            range: 'bytes=0-100'
        });

        if (!response.ok) throw new Error('请求失败');

        const contentType = response.headers.get('Content-Type');
        if (!contentType) return null;

        const mimeType = contentType.split(';')[0].trim().toLowerCase();

        const mimeToExt = {
            'image/jpeg': '.jpg',
            'image/png': '.png',
            'image/gif': '.gif',
            'image/webp': '.webp',
            'image/svg+xml': '.svg',
            'image/bmp': '.bmp'
        };

        return mimeToExt[mimeType] || null;
    } catch (error) {
        console.error('请求失败:', error);
        return null;
    }
}

export default app
